﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace TracertCMD
{
    class Program
    {

        static void Main()
        {
            string input = "119.23.23.244";

            TracertTemp tracert = new TracertTemp();
            tracert.TraceUpdate += Tracert_TraceUpdate;
            tracert.TraceFinished += Tracert_TraceFinished;
            tracert.TraceInitFinished += Tracert_TraceInitFinished;
            tracert.BeginTrack(input);

            Console.WriteLine("开始跟踪...");
            Console.ReadKey();
            tracert.CancelTrack();
            Console.WriteLine("已发送取消信息至Tracert，再次按下任意键退出程序");
            Console.ReadKey();
            tracert.CancelTrack();
        }

        private static void Tracert_TraceInitFinished(object sender, IPAddress e)
        {
            Console.WriteLine("初始化完毕，正在跟踪...");
        }

        private static void Tracert_TraceFinished(object sender, EventArgs e)
        {
            Console.WriteLine("跟踪结束");
        }

        private static void Tracert_TraceUpdate(object sender, TracertTemp.TraceEventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(e.TTL).Append("\t");
            foreach (var reply in e.PingReplies)
            {
                if (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.Success)
                {
                    if (reply.RoundtripTime == 0)
                    {
                        sb.Append("<1ms");
                    }
                    else
                    {
                        sb.Append(reply.RoundtripTime).Append("ms");
                    }
                }
                else
                {
                    sb.Append("*");
                }
                sb.Append("\t");
            }

            if (e.AverageDelay != -1.0)
            {
                var ip = (from n in e.PingReplies
                          where n.Status == IPStatus.TtlExpired || n.Status == IPStatus.Success
                          orderby n.RoundtripTime
                          select n.Address).ToArray()[0];

                sb.Append(ip.ToString());
            }
            else
            {
                sb.Append("\t*");
            }

            Console.WriteLine(sb.ToString());
        }
    }

}
